import io
import cv2
from flask import Flask, request, send_file, jsonify, make_response
from get_face_img import get_face_img
from PIL import Image
from flask_cors import CORS
import numpy as np
import base64
import json
from base64 import encodebytes
from gevent import pywsgi

app = Flask(__name__)

CORS(app)

def img_to_imgbs64utf8(img_np):
    """
    convert img_np to img_bs64
    """
    img_str = cv2.imencode('.jpg', img_np)[1].tobytes() #将图片编码成流数据，放到内存缓存中，然后转化成byte格式
    imgbs64 = base64.b64encode(img_str) # 编码为base64
    return imgbs64.decode('utf-8')

# 这个接口是服务器将图片接收
@app.route("/api/uploadFacePic/", methods=["GET", "POST"])
def put_change_pic():
    input_imgs = []
    imgs = request.files.getlist('upload')
    for img in imgs:
        input_imgs.append(cv2.imdecode(np.frombuffer(img.stream._file.getvalue(), np.uint8), cv2.IMREAD_COLOR))
        # cv2.imwrite('1.jpg', input_imgs[0])
    get_face_img(request.form, input_imgs)
    imgs_dict = {}
    for index, img in enumerate(input_imgs):
        imgs_dict[imgs[index].filename] = img_to_imgbs64utf8(img)

    return json.dumps(imgs_dict)

if __name__ == '__main__':
    keyfilename = './ssl/mcyhzc.top.key'
    certfilename = './ssl/mcyhzc.top_bundle.crt'
    server = pywsgi.WSGIServer(('0.0.0.0', 8080), app, keyfile=keyfilename,certfile=certfilename)
    server.serve_forever()
